<!-- 新增和修改 -->
<template>
  <div class="app-container">
    <Edialog
      :outershow="outershow"
      :title="title"
      @saveFn="saveFn"
      @close="closeFn"
      :saveClick="true"
      :width="type == 'add' ? '90%' : '50%'"
    >
      <el-row :gutter="20" v-if="type == 'add'" class="add-css">
        <el-col :span="13">
          <SpreadSheet
            v-if="outershow"
            style="height: 60vh; width: 100%"
            ref="Sheet"
            SheetName="Sheet1"
            :File="file"
            :Headers="headers"
            :ColumnWidth="200"
            :Records="records"
            @loaded="loaded"
            @cell-selected="cellSelected"
            @cells-selected="cellsSelected"
            @initA1="initA1"
            :onlyRead="true"
          ></SpreadSheet>
        </el-col>
        <el-col :span="11">
          <el-form ref="addForm" inline :model="form" label-width="80px">
            <!-- <el-form-item label="科目坐标" prop="subjectCode">
              <div>
                {{
                  form.sAddress
                    ? form.sAddress + "-" + form.eAddress
                    : form.subjectCode
                }}
              </div>
            </el-form-item> -->
            <el-form-item label="科目标识" prop="subjectCode">
              <div>
                {{
                  form.sAddress
                    ? form.sAddressName + "~" + form.eAddressName
                    : form.subjectSign
                }}
              </div>
            </el-form-item>
            <el-form-item label="科目信息" prop="name" v-if="!form.sAddress">
              <!-- <el-tooltip
                class="item"
                effect="dark"
                :content="form.text"
                placement="top-start"
              >
                <div class="ellipsis_text">
                  {{ form.text }}
                </div>
              </el-tooltip> -->
              <div>
                {{
                  `${form.subjectRowName || "--"}  | ${
                    form.subjectColName || "--"
                  } `
                }}
              </div>
            </el-form-item>
            <el-form-item label="科目条数" prop="name" v-else>
              <div class="ellipsis_text">
                {{ selectionData.length || 0 }}
              </div>
            </el-form-item>
            <el-form-item label="数据类型" prop="dataType">
              <el-select v-model="form.dataType">
                <el-option
                  v-for="item in dataTypeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="权限类型" prop="powerType">
              <el-select v-model="form.powerType">
                <el-option
                  v-for="item in powerTypeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <!-- v-if="!form.sAddress" -->
            <el-form-item label="科目类型" prop="isDynamic">
              <el-select v-model="form.isDynamic">
                <el-option
                  v-for="item in subjectTypeArr"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addItem">添加</el-button>
            </el-form-item></el-form
          >
          <el-row>
            <el-col :span="24">
              <el-table
                :data="tableData"
                border
                style="width: 100%"
                :height="tableHeight"
                v-loading="tableLoading"
              >
                <el-table-column
                  align="center"
                  type="index"
                  label="序号"
                  width="50"
                >
                </el-table-column>
                <template v-for="item in tableColumns">
                  <el-table-column
                    align="center"
                    :prop="item.prop"
                    :label="item.label"
                    :width="item.width"
                    :sortable="item.sortable"
                  >
                    <template slot-scope="scope">
                      <div v-if="item.prop == 'isDynamic'">
                        <el-select
                          v-model="scope.row.isDynamic"
                          @change="change(scope.row)"
                        >
                          <el-option
                            v-for="item in subjectTypeArr"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </div>
                      <div v-else-if="item.prop == 'dataType'">
                        <el-select v-model="scope.row.dataType">
                          <el-option
                            v-for="item in dataTypeArr"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </div>
                      <div v-else-if="item.prop == 'powerType'">
                        <el-select v-model="scope.row.powerType">
                          <el-option
                            v-for="item in powerTypeArr"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </div>
                      <!-- <span style="color: red" v-if="item.prop == 'name'">{{
                        scope.row[item.prop]
                      }}</span> -->

                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
                <el-table-column
                  fixed="right"
                  label="操作"
                  align="center"
                  width="100"
                >
                  <template slot-scope="scope">
                    <el-button
                      @click.native.prevent="
                        deleteItem(scope.$index, tableData)
                      "
                      type="text"
                      size="small"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-row style="margin-top: 10px">
                <el-checkbox v-model="isOver">是否覆盖旧数据</el-checkbox>
              </el-row>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-else-if="type == 'edit' || type == 'addOne'">
        <el-form
          ref="editForm"
          :model="editForm"
          label-width="100px"
          :rules="editRules"
        >
          <el-form-item label="科目标识" prop="subjectSign">
            <div v-if="type == 'edit'">
              {{ editForm.subjectSign }}
            </div>
            <el-input v-else v-model="editForm.subjectSign"></el-input>
          </el-form-item>
          <el-form-item
            label="科目坐标"
            prop="subjectCode"
            v-show="type == 'addOne'"
          >
            <el-input v-model="editForm.subjectCode"></el-input>
          </el-form-item>
          <el-form-item label="科目行名称" prop="subjectRowName">
            <el-input v-model="editForm.subjectRowName"></el-input>
          </el-form-item>
          <el-form-item label="科目列名称" prop="subjectColName">
            <el-input v-model="editForm.subjectColName"></el-input>
          </el-form-item>
          <el-form-item label="数据类型" prop="dataType">
            <el-select v-model="editForm.dataType">
              <el-option
                v-for="item in dataTypeArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="权限类型" prop="powerType">
            <el-select v-model="editForm.powerType">
              <el-option
                v-for="item in powerTypeArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="科目类型" prop="isDynamic">
            <el-select v-model="editForm.isDynamic">
              <el-option
                v-for="item in subjectTypeArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </el-row>
    </Edialog>
  </div>
</template>

<script>
import {
  indexToCoord,
  getNonEmptyMergedCells,
  coordToIndex,
  getColumnTitleValues,
  getRowTitleValues,
  updateCellAttributes,
} from "@/utils/spreadsheet.js";
import SpreadSheet from "@/components/Xspreadsheet/SpreadSheet.vue";
import Edialog from "@/components/Edialog";
import { getSelectData } from "@/utils/publicReq";
import {
  putBatchSaveApi,
  postBsSubjectApi,
  BsSubjectByIdApi,
  putBsSubjectApi,
} from "@/api/subjectConfig";
import { BsTemplateByIdApi } from "@/api/templateManage";
export default {
  data() {
    return {
      //是否覆盖
      isOver: false,
      tableData: [],
      tableLoading: false,
      tableHeight: "calc(60vh - 216px)",
      //表格字段
      tableColumns: [
        {
          prop: "subjectSign",
          label: "科目标识",
          width: "80",
        },
        {
          prop: "subjectCode",
          label: "科目坐标",
          width: "80",
        },
        {
          prop: "subjectRowName",
          label: "科目行名称",
          width: "120",
        },
        { prop: "subjectColName", label: "科目列名称", width: "120" },
        { prop: "isDynamic", label: "科目类型", width: "100" },
        { prop: "dataType", label: "数据类型", width: "100" },
        { prop: "powerType", label: "权限类型", width: "100" },
      ],
      file: null,
      ColumnCount: 30,
      RowCount: 100,
      headers: [],
      records: [],
      dataTypeArr: [],
      powerTypeArr: [],
      //swagger上copy的 是否动态科目(0:否；1：是)
      subjectTypeArr: [
        {
          value: "0",
          label: "静态",
        },
        {
          value: "1",
          label: "动态",
        },
      ],

      outershow: false,
      title: "新增",
      form: {
        subjectCode: "",
        subjectSign: "",
        text: "",
        sAddress: "",
        eAddress: "",
        powerType: "1",
        dataType: "1",
        isDynamic: "0",
        subjectRowName: "",
        subjectColName: "",
      },
      editForm: {
        subjectSign: "",
        subjectCode: "",
        subjectRowName: "",
        subjectColName: "",
        dataType: "",
        powerType: "",
        isDynamic: "0",
        templateId: "",
        excelJson: "",
      },
      editRules: {
        subjectSign: [
          { required: true, message: "请输入科目标识", trigger: "blur" },
        ],
        subjectCode: [
          { required: true, message: "请输入科目坐标", trigger: "blur" },
        ],
        dataType: [
          { required: true, message: "请选择数据类型", trigger: "blur" },
        ],
        powerType: [
          { required: true, message: "请选择权限类型", trigger: "blur" },
        ],
        isDynamic: [
          { required: true, message: "请选择科目类型", trigger: "blur" },
        ],
      },
      selectionData: [],
      spreadsheetData: [],
      type: "",
      templateId: "",
      templateCode: "",
    };
  },
  components: {
    Edialog,
    SpreadSheet,
  },
  computed: {
    // 获取表单ref
    formRef() {
      return this.type == "edit" || this.type == "addOne"
        ? this.$refs.editForm
        : this.$refs.addForm;
    },
  },
  async created() {
    this.dataTypeArr = await getSelectData("020701001");
    this.powerTypeArr = await getSelectData("020701002");
  },
  watch: {},
  methods: {
    change(val) {
      console.log("change", val);
      this.tableData.forEach((item) => {
        if (item.address == val.address) {
          item = val;
        }
      });
    },
    initA1(A1) {
      console.log("initA1", A1);
      if (A1) {
        setTimeout(() => {
          this.form.subjectCode = indexToCoord(0, 0);
          this.form.subjectSign = this.form.text = A1 && A1.text + "";
          this.$set(A1, "subjectCode", this.form.subjectCode);
          this.selectionData = [A1];
        });
      }
    },
    cellsSelected(cell, { sri, sci, eri, eci }) {
      console.log("cellsSelected", cell, { sri, sci, eri, eci });

      this.selectionData = [];
      this.form.sAddress = indexToCoord(sri, sci);
      this.form.eAddress = indexToCoord(eri, eci);
      this.form.sAddressName =
        (xs.sheet.data.getCell(sri, sci) &&
          xs.sheet.data.getCell(sri, sci).text) ||
        "-";
      this.form.eAddressName =
        (xs.sheet.data.getCell(eri, eci) &&
          xs.sheet.data.getCell(eri, eci).text) ||
        "-";
      // console.log("this.form.sAddressName,", this.form.eAddressName);

      this.form.subjectSign = this.form.text = cell && cell.text + "";
      const rangeData = xs.sheet.data.getData().rows;
      // 你当前表的名字
      // const target_sheet_name = xs.sheet.data.getData().name;
      // const target_data = xs.datas.find((it) => it.name === target_sheet_name);
      // console.log("xs.sheet.data.getData()", target_data.rows);
      // target_data.rows.setCell(
      //   sri,
      //   sci,
      //   {
      //     text: 1,
      //   },
      //   "all"
      // );
      this.selectionData = getNonEmptyMergedCells(rangeData, {
        sri,
        sci,
        eri,
        eci,
      });
      this.selectionData.forEach((item) => {
        // console.log("item", item);
        item.subjectSign = item.text;
        item.subjectCode = indexToCoord(item.row, item.col);
      });
    },
    cellSelected(cell, ri, ci) {
      if (cell && cell.isTitle) {
        return;
      }
      this.selectionData = [];
      console.log("cellSelected", cell, ri, ci);
      this.form.sAddress = "";
      this.form.eAddress = "";
      this.form.subjectColName = getColumnTitleValues(this.spreadsheetData, ci);
      this.form.subjectRowName = getRowTitleValues(this.spreadsheetData, ri);
      // this.$set(cell, "row", ri);
      // this.$set(cell, "col", ci);
      if (cell && cell._address) {
        this.form.subjectCode = cell._address;
      } else {
        this.form.subjectCode = indexToCoord(ri, ci);
      }
      if (cell) {
        cell.address = this.form.subjectCode;
        cell.subjectCode = this.form.subjectCode;

        this.form.subjectSign = this.form.text =
          (cell && cell.text + "") || "-";
        cell.subjectSign = this.form.subjectSign;
        this.selectionData = [cell];
      } else {
        this.selectionData = [];
      }

      console.log("selectionData", this.selectionData);
    },
    addItem() {
      let addTableData = this.$cloneDeep(this.selectionData);
      addTableData.forEach((newItem) => {
        console.log("newItem", newItem);

        let { rowIndex, colIndex } = coordToIndex(newItem.subjectCode);
        // 给表单数据添加表单中设置的数据属性
        let subjectRowName = getRowTitleValues(this.spreadsheetData, rowIndex);
        let subjectColName = getColumnTitleValues(
          this.spreadsheetData,
          colIndex
        );
        this.$set(newItem, "subjectRowName", subjectRowName);
        this.$set(newItem, "subjectColName", subjectColName);
        // this.$set(
        //   newItem,
        //   "isDynamic",
        //   this.form.sAddress ? "0" : this.form.isDynamic
        // );
        this.$set(newItem, "isDynamic", this.form.isDynamic);
        this.$set(newItem, "dataType", this.form.dataType);
        this.$set(newItem, "powerType", this.form.powerType);
        this.$set(newItem, "templateId", this.templateId);
        delete newItem.address;
        delete newItem.text;
        delete newItem.style;
        delete newItem.type;
        delete newItem.sharedFormula;
        delete newItem.formula;
        delete newItem.row;
        delete newItem.col;
        // 查找是否已存在相同address的对象
        const existingItemIndex = this.tableData.findIndex(
          (item) => item.subjectCode === newItem.subjectCode
        );
        // 检查是否isTitle属性为true
        if (newItem.isTitle === true) {
          // this.$message.warning("表头不能添加到科目中");
          console.warn("表头不能添加到科目中");
          return; // 跳过当前循环
        }
        if (existingItemIndex !== -1) {
          // 如果存在，则替换该对象
          this.$set(this.tableData, existingItemIndex, newItem);
        } else {
          // 如果不存在，添加新对象
          this.tableData.push(newItem);
        }
      });
    },
    saveFn() {
      console.log(
        "this.table",
        // this.spreadsheetData,
        // this.editForm,
        this.tableData
      );
      // return;
      if (this.type == "edit" || this.type == "addOne") {
        //单条科目
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            console.log("this.editForm", this.spreadsheetData);

            //给excelJson添加表单中设置的数据属性
            let { rowIndex, colIndex } = coordToIndex(
              this.editForm.subjectCode
            );
            //把表格json深拷贝出来
            let excelJson = this.$cloneDeep(this.spreadsheetData);
            updateCellAttributes(
              rowIndex,
              colIndex,
              {
                isDynamic: this.editForm.isDynamic,
                dataType: this.editForm.dataType,
                powerType: this.editForm.powerType,
                subjectSign: this.editForm.subjectSign,
              },
              excelJson
            );
            console.log("更新this.editForm", excelJson);
            this.editForm.excelJson = JSON.stringify(excelJson);
            this.editForm.templateId = this.templateId;
            if (this.type == "edit") {
              postBsSubjectApi(this.editForm).then((res) => {
                if (res.data && res.data.bcode == 0) {
                  this.$message.success(res.msg || "修改成功");
                }
                setTimeout(() => {
                  this.$emit("refreshFn");
                });
                this.closeFn();
              });
            } else if (this.type == "addOne") {
              console.log("addOne", this.editForm);

              putBsSubjectApi(this.editForm).then((res) => {
                if (res.data && res.data.bcode == 0) {
                  this.$message.success(res.msg || "新增成功");
                }
                setTimeout(() => {
                  this.$emit("refreshFn");
                });
                this.closeFn();
              });
            }
          }
        });
      } else if (this.type == "add") {
        //多条科目
        if (this.tableData.length == 0) {
          this.$message.error("请先添加科目");
          return;
        }
        let excelJson = this.$cloneDeep(this.spreadsheetData);
        this.tableData.forEach((item) => {
          let { rowIndex, colIndex } = coordToIndex(item.subjectCode);

          updateCellAttributes(
            rowIndex,
            colIndex,
            {
              isDynamic: item.isDynamic,
              dataType: item.dataType,
              powerType: item.powerType,
              subjectSign: item.subjectSign,
            },
            excelJson
          );
          console.log("excelJson循环", excelJson);
        });

        // return;
        let obj = {
          excelJson: JSON.stringify(excelJson),
          subjectList: this.tableData,
          templateCode: this.templateCode,
          isOver: this.isOver,
        };
        console.log("obj", obj);
        putBatchSaveApi(obj).then((res) => {
          console.log("res", res);
          if (res.data && res.data.bcode == 0) {
            this.$message.success(res.msg || "保存成功");

            setTimeout(() => {
              this.$emit("refreshFn");
            });

            this.closeFn();
          }
        });
      }
      // this.$message.success("修改成功");
    },
    deleteItem(index) {
      this.tableData.splice(index, 1);
    },
    //表格数据加载事件
    loaded(spreadsheet) {
      console.log("loaded", spreadsheet);
    },
    //外部打开弹窗
    async openFn(type, scope) {
      this.outershow = true;
      console.log("type", type, scope);
      this.type = type;
      this.templateId = scope.templateId;
      let api = await BsTemplateByIdApi(scope.templateId);
      if (api.data && api.data.bcode == 0) {
        // console.log("模板详情", api.data.bdata);
        this.spreadsheetData = JSON.parse(api.data.bdata.excelJson);
      }
      if (type == "add") {
        this.tableData = [];
        // this.spreadsheetData = JSON.parse(scope.excelJson);
        this.templateCode = scope.templateCode;
        this.title = "新增";
        setTimeout(() => {
          this.$refs.Sheet.loadData(this.spreadsheetData || []);
        });
      } else if (type === "edit") {
        this.spreadsheetData = JSON.parse(scope.excelJson);
        let res = await BsSubjectByIdApi(scope.id);
        console.log("res", res);
        if (res.data && res.data.bcode == 0) {
          this.$nextTick(() => {
            this.editForm = res.data.bdata;
            this.editForm.dataType = this.editForm.dataType + "";
            this.editForm.powerType = this.editForm.powerType + "";
            this.editForm.isDynamic = this.editForm.isDynamic + "";
          });
        } else {
          this.editForm = scope;
        }
        this.title = "修改";
      } else if (type == "addOne") {
        console.log("addOnescope", scope);
        this.spreadsheetData = JSON.parse(scope.excelJson);
        this.title = "单条新增";
      }
    },

    closeFn() {
      this.formRef.resetFields();
      this.outershow = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.el-select {
  width: 100%;
}
.add-css {
  .el-form-item {
    width: 45%;
    // display: flex;
  }
  ::v-deep .el-form-item__content {
    width: 60% !important;
  }
  .ellipsis_text {
    width: 200px; /* 或者你希望的固定宽度 */
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden; /* 隐藏超出容器的文本 */
    text-overflow: ellipsis; /* 使用省略号表示超出容器的文本 */
  }
}
</style>
